package service;

import common.Exception.Results;
import common.Exception.UserNameOrPasswordErrorException;
import dto.req.*;
import dto.resp.AuthorLoginRespDTO;
import dto.resp.GetAuthorCommentRespDTO;
import dto.resp.QueryOneArticleByIdRespDTO;
import entity.ArticleDO;
import entity.AuthorDO;
import service.impl.AuthorServiceImpl;
import util.JDBCUtils;

import javax.imageio.spi.ImageReaderWriterSpi;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;


public class AuthorService implements AuthorServiceImpl {
    private static final String tableName = "author";
    private ArticleService articleService;
    private ClickFavoriteService clickFavoriteService;
    private CommentArticleService commentArticleService;
    public AuthorService() {
        articleService = new ArticleService();
        clickFavoriteService = new ClickFavoriteService();
        commentArticleService = new CommentArticleService();
    }

    @Override
    public Results addUser(AuthorRegisterReqDTO user) {
        Results results = new Results();
        //TODO 数据校验
        if(user == null || user.getUsername() == null || user.getPassword() == null){
            return results.fail("用户不存在！");
        }
        if(user.getUsername().length() < 6  || user.getPassword().length() < 6){
            return results.fail("用户名或密码长度小于6个字符");
        }
        //进行插入操作，可能会导致插入失败
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = JDBCUtils.getConnection();
            //Statement statement = connection.createStatement();
            String sql = "INSERT INTO " + tableName + "(username, password,name) VALUES (?, ?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getName());

            // 执行SQL语句
            pstmt.executeUpdate();

            return results.success("注册成功！");
        } catch (Exception e) {
            return results.fail(e.getMessage());
        }finally {
            JDBCUtils.closeResource(connection,pstmt);
        }
    }

    @Override
    public Results<AuthorDO> queryUser(String username) {
        Results<AuthorDO> results = new Results<>();
        //TODO 数据校验
        if(username == null || username.length() < 6){
            return results.fail("用户名异常");
        }
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT id,username,name FROM " + tableName+ " WHERE username = ? " ;
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, username);
            // 执行SQL语句
            rs = pstmt.executeQuery();
            if(!rs.next()){
                //用户不存在
                return results.fail("查询的用户不存在");
            }
            AuthorDO authorDO = new AuthorDO();
            authorDO.setId(Integer.parseInt(rs.getString(1)));
            authorDO.setUsername(rs.getString(2));
            authorDO.setName(rs.getString(3));

            return results.success(authorDO,"查询成功！");
        } catch (Exception e) {
            return results.fail("查询异常： " + e.getMessage());
        }finally {
            JDBCUtils.closeResource(connection,pstmt,rs);
        }
    }

    /**
     * 用户注册持久层
     * @param user 用户实体
     * @return 是否注册成功
     */
    @Override
    public Results<AuthorLoginRespDTO> userLogin(AuthorLoginReqDTO user) {
        Results results = new Results();
        results.setData(null);
        //TODO 数据校验
        if(user == null || user.getUsername() == null || user.getPassword() == null){
            return results.fail("用户不存在");
        }
        if(user.getUsername().length() < 6  || user.getPassword().length() < 6){
            return results.fail("用户名或密码错误");
        }


        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT id,username,name FROM " + tableName+ " WHERE username = ? AND password = ?" ;
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());

            // 执行SQL语句
            rs = pstmt.executeQuery();
            if(!rs.next()){
                //用户不存在
                JDBCUtils.closeResource(connection,pstmt,rs);
                return results.fail("用户不存在");
            }
            AuthorLoginRespDTO author = new AuthorLoginRespDTO();
            author.setId(Integer.parseInt(rs.getString(1)));
            author.setUsername(rs.getString(2));
            author.setName(rs.getString(3));
            results.setData(author);
            return results.success("登录成功");
        }catch (UserNameOrPasswordErrorException e){
            return results.fail("用户名或密码错误");
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            return results.fail("异常: " + e.getMessage());
        }finally {
            JDBCUtils.closeResource(connection,pstmt,rs);
        }
    }

    @Override
    public Results addArticle(AuthorPublishArticleReqDTO articleDO) {
        Results results = new Results();
        //TODO 对用户数据做校验
        if(articleDO.getAuthorId() == null){
            return results.fail("用户不存在");
        }
        if(articleDO == null ){
            return results.fail("用户名或密码错误");
        }
        if(articleDO.getTitle() == null || articleDO.getContext() == null || articleDO.getAuthorId() == null ){
            return results.fail("标题或正文为空");
        }
        if(articleDO.getTitle().length() < 6){
            return results.fail("标题不得少于六个字符");
        }
        if(articleDO.getContext().length() < 10){
            return results.fail("正文不得少于十个字符");
        }
        boolean b = articleService.addArticle(articleDO);
        if(!b){
            return results.fail("发布文章失败");
        }
        return results.success("发布文章成功！");
    }

    @Override
    public Results updateArticleTitle(UpdateArticleTitleReqDTO request) {
        Results results = new Results();
        //TODO 对用户数据做校验
        if(request.getAuthorId() == null){
            return results.fail("用户不存在");
        }
        if(request.getArticleId() == null){
            return results.fail("文章不存在或新标题为空");
        }
        if(request.getNewTitle() == null ){
            return results.fail("文章异常");
        }
        if(request.getNewTitle().length() < 6){
            return results.fail("标题不得少于六个字符");
        }
        return articleService.updateArticleTitle(request);
    }

    @Override
    public Results updateArticleContext(UpdateArticleContextReqDTO request) {
        Results results = new Results();

        if(request.getAuthorId() == null){
            return results.fail("用户不存在");
        }
        if(request.getArticleId() == null || request.getNewContext() == null){
            return results.fail("文章不存在或新正文为空");
        }
        if(request.getNewContext().length() < 10){
            return results.fail("正文不得少于10个字符");
        }
        return articleService.updateArticleContext(request);
    }

    /**
     * 点赞功能
     * @param articleId
     * @param authorId
     * @return
     */
    @Override
    public Results clickFavorite(Integer articleId,Integer authorId) {
        //数据校验
        Results results = new Results();
        if(authorId == null){
            return results.fail("文章ID异常");
        }
        if(authorId == null){
            return results.fail("登录用户异常");
        }

        /**
         * 查询文章是否存在
         */
        Results<QueryOneArticleByIdRespDTO> articleDO = articleService.queryOneArticleById(articleId);
        if(articleDO == null){
            return results.fail("点赞文章异常: 文章ID不存在");
        }
        //判断当前用户是否已经给文章点赞
        boolean b = clickFavoriteService.queryiSClick(articleId, authorId);
        if(b){
            return results.fail("该文章你已经点过赞了");
        }
        //给文章点赞数 + 1
        //添加点赞记录
        boolean isClickSuccess = clickFavoriteService.addNumber(articleId, authorId);
        if(!isClickSuccess){
            return results.fail("添加点赞记录异常");
        }

        //更新赞的数量
        boolean clickFavoriteIsSuccess = articleService.clickFavorite(articleId);
        if(!clickFavoriteIsSuccess){
            return results.fail("点赞更新出现异常");
        }
        return results.success("点赞成功");
    }

    @Override
    public Results commentArticle(AuthorCommentReqDTO request) {
        //数据校验
        Results results = new Results();
        if(request.getArticleId() == null){
            return results.fail("文章ID异常");
        }
        if(request.getAuthorId() == null){
            return results.fail("登录用户异常");
        }
        if(request.getComment() == null || request.getComment().length() < 1){
            return results.fail("评论不能为空");
        }

        /**
         * 查询文章是否存在
         */
        Results<QueryOneArticleByIdRespDTO> results1 = articleService.queryOneArticleById(request.getArticleId());
        QueryOneArticleByIdRespDTO data = results1.getData();
        if(data == null){
            return results.fail("评论文章异常: 文章ID不存在");
        }

        //添加评论记录
        boolean isClickSuccess = commentArticleService.addComment(request);
        if(!isClickSuccess){
            return results.fail("添加评论记录异常");
        }
        return results.success("评论成功");
    }

    @Override
    public Results deleteArticle(Integer articleId, Integer authorId) {
        Results results = new Results();
        if(articleId == null){
            return  results.fail("文章不存在");
        }
        if(authorId == null){
            return results.fail("用户不存在");
        }
        AuthorDeleteArticleReqDTO request = new AuthorDeleteArticleReqDTO(authorId,articleId);
        return articleService.deleteArticle(request);
    }

    @Override
    public Results<QueryOneArticleByIdRespDTO> queryOneArticleById(Integer articleId) {
        if(articleId == null){
            return null;
        }
        return articleService.queryOneArticleById(articleId);
    }

    @Override
    public Results<GetAuthorCommentRespDTO> queryUserById(Integer id) {
        Results<GetAuthorCommentRespDTO> results = new Results<>();
        //TODO 数据校验
        if(id == null ){
            return results.fail("用户不存在");
        }
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = JDBCUtils.getConnection();
            String sql = "SELECT name FROM " + tableName+ " WHERE id = ? " ;
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, id);
            // 执行SQL语句
            rs = pstmt.executeQuery();
            if(!rs.next()){
                //用户不存在
                return results.fail("查询的用户不存在");
            }
            GetAuthorCommentRespDTO authoName = new GetAuthorCommentRespDTO();
            authoName.setName(rs.getString(1));
            return results.success(authoName,"查询成功！");
        } catch (Exception e) {
            return results.fail("查询异常： " + e.getMessage());
        }finally {
            JDBCUtils.closeResource(connection,pstmt,rs);
        }
    }

    @Override
    public Results<ArrayList<QueryOneArticleByIdRespDTO>> queryAllArticleByAuthorId(Integer autthorId) {
        if(autthorId == null){
            Results    results = new Results();
            return results.fail("作者不存在");
        }
        return articleService.queryAllArticleByAuthorId(autthorId);
    }


}
